﻿using FastBuild.TimeJob;
using Newtonsoft.Json.Linq;
using SqlSugar;
using Wechat_PublicNumber.Common;
using Wechat_PublicNumber.Entity;
using Wechat_PublicNumber.Model.Input.PublicNumberPushTemplate;
using Wechat_PublicNumber.Repository;

namespace Wechat_PublicNumber.Jobs
{
    /// <summary>
    /// 股票涨跌幅
    /// </summary>
    [SkipWhileExecuting]
    public class StockEndJob : DataAccess, IJob
    {
        [Autowired]
        private CommonHttpInvoke _commonHttpInvoke;

        [Autowired]
        private WxTemplateRepository _templateRepository;

        [Autowired]
        private WxHttpInvoke _wxHttpInvoke;

        private string stocktemp = "{stockname}：{stockprice} {stockchg} {stockpercent}";

        public async Task Execute()
        {
            var nowTime = DateTime.Now;
#if RELEASE
                //非股票交易时间
                if (!StockTime.OpeningQuotation ||
                    //加10秒是因为午盘最后的集合竞价会有延迟性，会导致推送数据的不准确
                     (!nowTime.BetweenOffset(StockTime.MorningEndTime.AddSeconds(10), TimeSpan.FromSeconds(1))
                    && !nowTime.BetweenOffset(StockTime.NoonEndTime.AddSeconds(10), TimeSpan.FromSeconds(1)))
                    )
                    return;
#endif

            //获取所有人的设置列表
            var allSet = await WXDb.Queryable<UserStock, Stock, UserInfo>((us, stock, users) => new object[]
               {
                          JoinType.Inner, stock.ID== us.StockID,
                          JoinType.Inner, users.OpenID== us.OpenID
               })
             .Distinct()
             .Select((us, stock, users) => new
             {
                 stock.ID,
                 stock.StockName,
                 stock.StockCode,
                 stock.BelongStockExchange,
                 us.OpenID
             })
             .ToListAsync();

            //获取所有股票
            var allStockCode = allSet.Select(s => s.BelongStockExchange + s.StockCode).Distinct().ToList();
            if (allStockCode.Count <= 0) return;

            var realStockList = await _commonHttpInvoke.GetRealTimeStock(allStockCode);

            var stockEndTempList = realStockList.Select(r =>
             {
                 //获取所有当前股票的用户
                 var oneStockUserList = allSet.Where(s => (s.BelongStockExchange + s.StockCode) == r.symbol).ToList();

                 return new StockEndTemp()
                 {
                     stockname = oneStockUserList[0].StockName,
                     stockcode = r.symbol,
                     stockprice = r.current,
                     stockchg = r.chg,
                     stockpercent = r.percent
                 };
             }).ToList();

            #region Send StockEndTemplate
            Dictionary<string, string> stockEndTempDic = new Dictionary<string, string>();

            var propertyInfos = stockEndTempList[0].GetType().GetProperties();
            stockEndTempList.ForEach(s =>
            {
                var newStockTemp = stocktemp;
                foreach (var property in propertyInfos)
                {
                    var value = property.GetValue(s).ToString();

                    if (property.Name == nameof(s.stockname) && value.Length < 4)
                        value += new string('\u3000', (4 - value.Length) * 1);

                    if (property.Name == nameof(s.stockchg) || property.Name == nameof(s.stockpercent))
                    {
                        value = decimal.Parse(value).PaddingCharRigth(2, ' ', 2);

                        if (!value.StartsWith("-")) value = $"+{value}";
                    }

                    if (property.Name == nameof(s.stockprice))
                        value = decimal.Parse(value).PaddingCharRigth(3, ' ', 2);

                    newStockTemp = newStockTemp.Replace($"{{{property.Name}}}", value);
                }

                newStockTemp = newStockTemp.TrimEnd(' ') + "%";

                stockEndTempDic.Add(s.stockcode, newStockTemp);
            });

            var tempPropertyInfos = typeof(StockEndTemplateInput).GetProperties();

            foreach (var group in allSet.GroupBy(s => s.OpenID))
            {
                var list = group.OrderByDescending(g => g.StockName.Length).Select(g => new { g.BelongStockExchange, g.StockCode }).Distinct().ToList();

                for (int t = 0; t < list.Count / 5 + (list.Count % 5 != 0 ? 1 : 0); t++)
                {
                    StockEndTemplateInput stockEndTemplateInput = new StockEndTemplateInput();
                    var newList = list.Skip(t * 5).Take(5).ToList();

                    for (int i = 1; i <= newList.Count; i++)
                    {
                        var tempProperty = tempPropertyInfos.Where(t => t.Name == $"stock{i}").FirstOrDefault();
                        if (tempProperty != null)
                        {
                            tempProperty.SetValue(stockEndTemplateInput, stockEndTempDic.Where(s => s.Key == newList[i - 1].BelongStockExchange + newList[i - 1].StockCode).First().Value);
                        }
                    }
                    var pushData = await _templateRepository.GetTemplateData(Model.WeChatTemplateEnum.StockEnd, group.Key, stockEndTemplateInput);

                    await _wxHttpInvoke.PushTemplate(pushData);
                }
            }
            #endregion

            _logger.Info($"StockEndJob Successfully executed", "StockEndJob");
        }
    }

    public class StockEndTemp
    {
        public string stockname { get; set; }

        public string stockcode { get; set; }

        public decimal stockprice { get; set; }

        public decimal stockpercent { get; set; }

        public decimal stockchg { get; set; }
    }
}
